package org.moore.utils;

import org.moore.controller.Application;
import org.moore.model.Map;
import org.moore.model.User;

import javax.swing.*;
import java.sql.*;

// 存档工具类
public class SaveMapUtils {

    // 将二维数组转成字符串
    public static String arrayToString(int[][] array) {
        StringBuilder sb = new StringBuilder();
        for (int[] row : array) {
            for (int val : row) {
                sb.append(val).append(",");
            }
            sb.append(";");
        }
        return sb.toString();
    }

    // 将字符串转成二维数组
    public static int[][] stringToArray(String str) {
        String[] rows = str.split(";");
        int[][] array = new int[rows.length][];
        for (int i = 0; i < rows.length; i++) {
            String[] vals = rows[i].split(",");
            array[i] = new int[vals.length];
            for (int j = 0; j < vals.length; j++) {
                array[i][j] = Integer.parseInt(vals[j]);
            }
        }
        return array;
    }

    // 保存存档的方法
    public static int saveMap() {
        // 反射
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("依赖加载成功！！！"); //测试语句，后续忽略
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("依赖加载失败......"); //测试语句
        }
        System.out.println("开始数据库操作......"); //测试语句
        // JDBC
        // 定义SQL语句
        String sql = "INSERT INTO t_save (`name`,user_id,gameMode,gameLevel,steps,time,score,maxScore,map) VAlUES (?,?,?,?,?,?,?,?,?)";
        Connection conn = null;
        PreparedStatement pst = null;
        try {
            // 获取连接
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jf240503db", "Moore", "123456");
            // 创建会话对象 预编译对象
            pst = conn.prepareStatement(sql);
            String name = JOptionPane.showInputDialog(null,"请输入存档名：");
            pst.setString(1,name);
            pst.setInt(2, User.getId());
            pst.setInt(3, Map.isMapType());
            pst.setInt(4, Map.getLevel());
            pst.setInt(5, Data.STEPS);
            pst.setInt(6, Countdown.getSeconds());
            pst.setInt(7, Data.SCORE);
            pst.setInt(8, Application.getMaxScore());
            String arrayStr = arrayToString(Map.getSaveMap());
            pst.setString(9, arrayStr);
            // 使用会话对象，执行sql语句 返回 受影响的条数
            int result = pst.executeUpdate();
            if (result > 0) {
                return result;
            }
            // 使用会话对象，执行sql语句 返回受影响的条数
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (pst != null) {
                try {
                    pst.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return -1;
    }

    // 读取存档文本的方法
    public static String roadMapText(int userId, int num) {
        // 创建文本内容
        String mode = "";
        String level = "";
        StringBuilder str = new StringBuilder();
        // 反射
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        // JDBC
        // 定义SQL语句
        String sql = "SELECT * FROM t_save WHERE user_id = ? ORDER BY insertTime DESC LIMIT 1 OFFSET ?";
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            // 获取连接
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jf240503db", "Moore", "123456");
            // 创建会话对象
            pst = conn.prepareStatement(sql);
            pst.setInt(1,userId);
            pst.setInt(2,num);
            // 使用会话对象，执行sql语句
            // 执行查询语句并返回查询的结果集
            rs = pst.executeQuery();
            while (rs.next()) {
                // 如果有下个元素
                String name = rs.getString("name");
                int gameMode = rs.getInt("gameMode");
                int gameLevel = rs.getInt("gameLevel");
                int steps = rs.getInt("steps");
                int time = rs.getInt("time");
                int score = rs.getInt("score");
                // 判断游戏模式跟关卡
                if (gameMode == 1){
                    mode = "步数";
                } else if (gameMode == 2) {
                    mode = "时间";
                }
                if (gameLevel == 1){
                    level = "低级";
                } else if (gameLevel == 2){
                    level = "中级";
                } else if (gameLevel == 3){
                    level = "高级";
                }
                str.append("<html>存档名称：").append(name).append("<br>游戏模式：").append(mode).append(level).append("<br>游戏步数：").append(steps).append("<br>游戏时间：").append(time).append("<br>最高分数：").append(score);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (rs != null) {
                try {
                    rs.close();
                } catch(SQLException e) {
                    e.printStackTrace();
                }
            }
            if (pst != null) {
                try {
                    pst.close();
                } catch(SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch(SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return str.toString();
    }

    // 读取地图属性
    public static int[][] roadMap(int userId, int num) {
        // 反射
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        // JDBC
        // 定义SQL语句
        String sql = "SELECT * FROM t_save WHERE user_id = ? ORDER BY insertTime DESC LIMIT 1 OFFSET ?";
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        int[][] array = null;
        try {
            // 获取连接
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jf240503db", "Moore", "123456");
            // 创建会话对象
            pst = conn.prepareStatement(sql);
            pst.setInt(1,userId);
            pst.setInt(2,num);
            // 使用会话对象，执行sql语句
            // 执行查询语句并返回查询的结果集
            rs = pst.executeQuery();
            while (rs.next()) {
                Map.setMapType(rs.getInt("gameMode"));
                Map.setLevel(rs.getInt("gameLevel"));
                if (Map.isMapType() == 1){
                    Data.STEPS = rs.getInt("steps");
                } else if (Map.isMapType() == 2) {
                    try {
                        Countdown.pause();
                    } catch (Exception ex) {
                        System.out.println();
                    }
                    new Countdown(rs.getInt("time"));
                }
                Data.SCORE = rs.getInt("score");
                String arrayStr = rs.getString("map");
                array = stringToArray(arrayStr);
                Data.COUNT = 0;
                Data.CUSTOM = 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (pst != null) {
                try {
                    pst.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return array;
    }

}
